//
//  JKOAuthViewController.swift
//  JKWeibo
//
//  Created by albert on 16/5/14.
//  Copyright © 2016年 albert. All rights reserved.
//  授权界面

import UIKit
import SVProgressHUD

class JKOAuthViewController: UIViewController {

    /** 网页容器 */
    @IBOutlet weak var myOAuthWebView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 1.定义字符串保存登录界面URL
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(JKAppKey)&redirect_uri=\(JKRedirect_uri)"
        // 2.创建URL
        guard let url = NSURL(string: urlStr) else {
            return
        }
        // 3.创建reuqest
        let request = NSURLRequest(URL: url)
        // 4.加载登录界面
        myOAuthWebView.loadRequest(request)
    }
    
    @IBAction func backBtnClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 调试技巧，自动填充网页帐号和密码
    @IBAction func autoFillBtnClick() {
        let jsStr = "document.getElementById('userId').value = 'aaaaaa';document.getElementById('passwd').value = 'aaaaaa';"
        myOAuthWebView.stringByEvaluatingJavaScriptFromString(jsStr)
    }
}

extension JKOAuthViewController: UIWebViewDelegate{
    
    // 开始加载
    func webViewDidStartLoad(webView: UIWebView) {
            SVProgressHUD.showWithStatus("正在加载...")
            SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
    }
    
    // 加载结束
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.showSuccessWithStatus("加载成功！")
        SVProgressHUD.dismissWithDelay(0.25)
    }
    
    // 该方法每次请求都会调用
    // 如果返回false代表不允许请求，如果返回true代表允许请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        // 1.判断当前是否是授权回调页面
        guard let urlStr = request.URL?.absoluteString else {
            return false
        }
        
        // 不是授权页面才允许加载
        if !urlStr.hasPrefix(JKRedirect_uri) {
            
            JKLog("不是授权回调页面")
            return true
        }
        
        JKLog("是授权回调页面")
        // 2.判断授权回调地址中参数是否以code=开头
        // URL的query属性是转没用来获取URL中的参数的，可以获取URL中?后面的所有内容
        let key = "code="
        // 判断URL参数是否有值
        guard let str = request.URL!.query else {
            return false
        }
        
        if str.hasPrefix(key) {
            // 获取授权code
            // 注意每次授权返回的code不一样
            let code = str.substringFromIndex(key.endIndex)
            
            // 发送请求 获取AccessToken
            loadAccessToken(code)
        }
        
        return false
    }
    
    //MARK: - 发送请求 获取AccessToken
    private func loadAccessToken(codeStr: String?){

        guard let code = codeStr else {
            return
        }
        
        // 1.创建路径
        let path = "oauth2/access_token"
        // 2.请求参数
        let parameters = ["client_id" : JKAppKey, "client_secret" : JKAppSecret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : JKRedirect_uri]
        // 3.发送请求
        JKNetworkingTool.sharedInstance.POST(path, parameters: parameters, success: { (task: NSURLSessionDataTask, objc: AnyObject) -> Void in
            
            // 创建account模型
            let account = JKUserAccount(dict: objc as! [String : AnyObject])
            
            // 获取用户信息并归档
            account.loadUserInfo({ (account, error) -> () in
                account?.saveAccount()
               
                SVProgressHUD.showSuccessWithStatus("授权成功！")
                SVProgressHUD.dismissWithDelay(0.25)
                
                // 记住modal出来的控制器要切换的话，先dismiss
                self.dismissViewControllerAnimated(true, completion: { () -> Void in
                    // 发出切换到欢迎界面的通知
                    NSNotificationCenter.defaultCenter().postNotificationName(JKSwitchRootViewControllerNotification, object: nil, userInfo: [JKSwitchRootViewControllerKey : JKSwitchToWelcomeValue])
                })
            })

            }) { (task: NSURLSessionDataTask?, error: NSError?) -> Void in
                JKLog(error)
        }
    }
}